package base.test7.reducejoin;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import org.checkerframework.checker.units.qual.A;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;

public class TableReducer extends Reducer<Text,TableBean, NullWritable,TableBean> {

    @Override
    protected void reduce(Text key, Iterable<TableBean> values, Context context) throws IOException, InterruptedException {

        ArrayList<TableBean> orderBeans = new ArrayList<>();
        TableBean pdBean = new TableBean();
        for(TableBean value : values){
            if("order".equals(value.getFlag())){
                //创建一个临时的Bean来接收value
                TableBean tempBean = new TableBean();
                try {
                    //将value拷贝给tempBean对象(这里有深拷贝浅拷贝的原因，所以不能直接add（value）
                    BeanUtils.copyProperties(tempBean,value);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
                orderBeans.add(tempBean);
            }else{
                try {
                    BeanUtils.copyProperties(pdBean,value);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        for(TableBean orderBean : orderBeans){

            orderBean.setpName(pdBean.getpName());

            context.write(NullWritable.get(),orderBean);
        }
    }
}
